/*
 * Copyright 1999-2101 Alibaba Group.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.dubbo.governance.web.governance.module.screen;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.governance.service.CacheService;
import com.alibaba.dubbo.governance.service.ConsumerService;
import com.alibaba.dubbo.governance.service.OverrideService;
import com.alibaba.dubbo.governance.service.ProviderService;
import com.alibaba.dubbo.governance.web.common.module.screen.Restful;
import com.alibaba.dubbo.registry.common.domain.Cache;
import com.alibaba.dubbo.registry.common.domain.Consumer;
import com.alibaba.dubbo.registry.common.domain.Override;
import com.alibaba.dubbo.registry.common.domain.Provider;
import com.alibaba.dubbo.registry.common.domain.Service;
import com.alibaba.fastjson.JSON;

/**
 * @author shihui
 */
public class Caches  extends Restful {
    @Autowired
    private CacheService cacheService;
    
    @Autowired
    private ProviderService providerService;
    
    @Autowired
    private ConsumerService consumerService;
    
    @Autowired
    private OverrideService overrideService;
    
    public void index(Map<String, Object> context) {
        String service = (String) context.get("service");   //搜索框参数：服务名
        String application = (String) context.get("application");   //搜索框参数：应用名
        String address = (String) context.get("address");    //搜索框参数：机器IP
        
        List<Service> services = new ArrayList<Service>();
        if(StringUtils.isEmpty(service) && StringUtils.isEmpty(application) && StringUtils.isEmpty(address)) {
        	List<String> serviceList = cacheService.findCacheServices();  //取到所有有cache配置的服务名
        	for (String serviceName : serviceList) {
            	services.add(getServiceObj(serviceName, null, null));
			}
        } else {
        	services.add(getServiceObj(service, address, application));
        	context.put("show", true);  //按照条件搜索出来的结果显示所有方法
        }
        context.put("services", services);
    }
    
    private Service getServiceObj(String service, String address, String application) {
    	Service serviceObj = new Service();
		List<Provider> providers = providerService.findByParams(service, address, application);
		List<Cache> caches = cacheService.findByParams(service, address, application);
    	List<Consumer> consumers = consumerService.findByParams(service, address, application);
    	serviceObj.setService(service);
    	serviceObj.setCaches(caches);
    	serviceObj.setProviders(providers);
    	serviceObj.setConsumers(consumers);
    	return serviceObj;
    }
    
    /**
     * 启用或禁用
     * */
    public boolean toDo(Map<String, Object> context) {
    	String method = (String) context.get("method");
		if(StringUtils.isEmpty(method)) {
			context.put("message", "have no method");
	        return false;
		}
    	String service = (String) context.get("service");
		if (!super.currentUser.hasServicePrivilege(service)) {
	        context.put("message", getMessage("HaveNoServicePrivilege", service));
	        return false;
	    }
		
		String overrideIdStr = (String) context.get("overrideId");
		//创建新的cache
		if(StringUtils.isEmpty(overrideIdStr)) {
		} else { //修改已有的cache
			overrideService.deleteOverrides(context.get("overrideId").toString().split(Constants.COMMA_SEPARATOR));
		    create(context);
		}
		return create(context);
    }
    
    /**
     * 创建新的cache配置
     * */
   boolean create(Map<String, Object> context) {
	   try {
	   		String method = context.get("method").toString();
	 		Map<String, Object> paramValues = catchParams(context, method);
	 		List<String> applications = (List<String>) paramValues.get(Constants.APPLICATION_KEY);
	 		paramValues.remove(Constants.APPLICATION_KEY);  //从map中移出
	 		if(applications.isEmpty()) {  //没有指定应用
	 			com.alibaba.dubbo.registry.common.domain.Override override = createOverride(paramValues, context);
	     		overrideService.saveOverride(override);
	     	} else { 
	     		for (int i = 0; i < applications.size(); i++) {  //一个应用对应一个override
	 				String application = applications.get(i);
	 				com.alibaba.dubbo.registry.common.domain.Override override = createOverride(paramValues, context);
	 				override.setApplication(application);//application直接设置到override，不需要拼接到param上
	 				overrideService.saveOverride(override);
				}
	     	}
	        return true;
	   	} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
   }
   
   /**
    * 根据参数构造override
    * */
   Override createOverride(Map<String, Object> paramValues, Map<String, Object> context) throws Exception {
	   //封装override类
		com.alibaba.dubbo.registry.common.domain.Override override = new com.alibaba.dubbo.registry.common.domain.Override();
		override.setService(context.get("service").toString());
		Map<String, String> cache2Value = new HashMap<String, String>();
 		for(Map.Entry<String, Object> param : paramValues.entrySet()) {
 			String key = param.getKey();
 			String value = param.getValue().toString();
 			if(isEqualDefault(key, value)) continue;  //新增时的参数值若跟默认值一致，则过滤
 			cache2Value.put(key, value);
 		}
 		
     	override.setEnabled(true); //默认为开启
     	//拼接参数
     	StringBuilder paramters = new StringBuilder();
     	boolean isFirst = true;
         for(Map.Entry<String, String> e : cache2Value.entrySet()) {
             if(isFirst) isFirst = false;
             else paramters.append("&");
             paramters.append(e.getKey()).append("=").append(URL.encode(e.getValue()));
         }
         override.setParams(paramters.toString());   //设置参数
		return override;
   }
   
   /**
    * 取参数
 * @throws Exception 
    * */
   Map<String, Object> catchParams(Map<String, Object> context, String method) throws Exception {
	   Map<String, Object> cache2Value = new HashMap<String, Object>();
	   List<String> applications = new ArrayList<String>();
	   for(Map.Entry<String, Object> param : context.entrySet()) {
           String key = param.getKey().trim();  //参数名
           if(! (param.getValue() instanceof String) ) continue;  //过滤掉无关的其他参数
           String value = (String) param.getValue();  //参数值
			if(key.startsWith(method) && !StringUtils.isBlank(value)) {
                 if(key.startsWith(method + "_application_")) {
                	 applications.add(key.substring((method + "_application_").length()));
                 } else {
                	cache2Value.put(key, value);
                 }
             }
       }
	   cache2Value.put(Constants.APPLICATION_KEY, applications);
	   return cache2Value;
   }

   /**
    * 用页面传入的cache参数值与默认值做比较
    * */
   boolean isEqualDefault(String key, String value) throws Exception {
	   if(!key.contains(".cache.")) return false;
	   Class<Cache> cls = Cache.class;
	   Cache cache = cls.newInstance();
	   String propertyName = key.substring(key.lastIndexOf(".")+1);
	   PropertyDescriptor pd = new PropertyDescriptor(propertyName, cls);
	   Method m = pd.getReadMethod();  //取到属性对应get方法
	   Object val = m.invoke(cache);  //取cache对象属性对应的默认值
	   if(val != null && val.toString().equals(value)) {   //若接收到的参数值跟默认值一样则未做修改，直接过滤
		   return true;
	   }
	   return false;
   }
   
   public void caches(Map<String, Object> context) {
	   try {
		   List<Service> services = new ArrayList<Service>();
		   List<String> serviceList = cacheService.findCacheServices();  //取到所有有cache配置的服务名
		   for (String serviceName : serviceList) {
			  List<Cache> caches = cacheService.getCachesByService(serviceName);
			  Service service = new Service();
			  service.setCaches(caches);
			  service.setService(serviceName);
			  services.add(service);
	   	   }
		   context.put("hideLayout", true);   //不显示layout
		   context.put("cachesJson", JSON.toJSONString(services));
		} catch (Exception e) {
			e.printStackTrace();
		}
   }
}
